﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.AnalysisServices.SharePoint.Integration;

namespace UpdatePowerPivot
{
    public class CustomDataRefreshUtils
    {

        public static GeminiServiceApplicationProxy GetDefaultProxy(string url)
        {
            GeminiServiceApplicationProxy defaultProxy = null;
            if (null != SPServiceContext.Current)
            {
                defaultProxy = (GeminiServiceApplicationProxy)SPServiceContext.Current.GetDefaultProxy(typeof(GeminiServiceApplicationProxy));
            }
            else
            {
                SPSite sPSite = new SPSite(url);
                defaultProxy = (GeminiServiceApplicationProxy)SPServiceContext.GetContext(sPSite).GetDefaultProxy(typeof(GeminiServiceApplicationProxy));
                defaultProxy.CurrentSite = sPSite;
            }

            return defaultProxy;
        }

        public static DataRefreshSchedule GetRefreshScheduls(string documentUrl, bool loadDataSources)
        {
            using (SPSite site = new SPSite(documentUrl))
            {
                SPWeb web = null;
                try
                {
                    SPFile file = null;
                    if (SPContext.Current != null)
                        file = SPContext.Current.Web.GetFile(documentUrl);
                    else
                    {
                        web = site.OpenWeb();
                        file = web.GetFile(documentUrl);
                    }
                    Guid uniqueId = file.UniqueId;
                    try
                    {
                        return GetDefaultProxy(documentUrl).GetDataRefreshSchedule(documentUrl, uniqueId, loadDataSources);
                    }
                    catch (Exception ex)
                    {
                        return null;
                    }
                }
                finally
                {
                    if (web != null)
                        web.Dispose();
                }
            }
        }

        public static bool PersistDataRefreshSchedule(DataRefreshSchedule drs, string url)
        {
            try
            {
                GeminiServiceApplicationProxy proxy = GetDefaultProxy(url);

                drs.RunNow = true;
                proxy.PersistDataRefreshSchedule(drs);
                return true;
            }
            catch (Exception faultException)
            {
                return false;
            }
        }
    }
}
